<?php

namespace App\Services\SetGoldBudget;

use Carbon\Carbon;
use App\Models\User;
use App\Models\GoldRound;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class EnterFromGoldBudgetRequest extends FormRequest
{
	public function rules()
	{
		return [
			'rid' => [
				'required',
				'integer',
				'min:1',
				$this->rid(),
			]
		];
	}
	
	public function attributes()
	{
		return [
			'rid' => '场次',
		];
	}
	
	public function rid()
	{
		return function ($key, $value, $fail) {
			
			/**
			 * @var User $user
			 */
			$user = $this->user();
			
			$rid = $this->rid;
			
			$time = Carbon::now();
			
			if ($time->lt(GoldRound::todayOpenedAt($rid))) {
				return $fail('本场尚未开场');
			} elseif ($time->gt(GoldRound::todayEndedAt($rid))) {
				return $fail('本场已经结束');
			} elseif ($time->gte(GoldRound::todayStartedAt($rid))
				and $time->lte(GoldRound::todayEndedAt($rid))) {
				return $fail('抢购中不可操作');
			} elseif (! $user->hasGoldBudgetCache($rid)) {
				return $fail('请先设置抢单预算');
			} elseif ($user->isInGoldEnterCache($rid)) {
				return $fail('抢单中请勿重复提交');
			}
			
			return true;
		};
	}
}
